#!/bin/env python
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from PIL import Image
import numpy as np
import time
import cv2

# define
home_page = 'http://www.3366.com/'
game_page = 'http://www.3366.com/flash/1000239.shtml'
tmp_img_dir = '/home/solideo/Works/click_game/imgs/'
qq_account = 'QQ 账号'
qq_password = 'QQ 密码'
wait_time = 3
location = 0
size = 0

driver = webdriver.Chrome()
driver.set_window_size(1366, 768)


def login():
    driver.get(home_page)

    # 加载登录框
    driver.find_element(By.CLASS_NAME, 'btn_login').click()
    driver.implicitly_wait(wait_time)
    time.sleep(1)

    # 切入iframe
    driver.switch_to.frame(driver.find_element(By.ID, 'loginFrame'))

    # 选择账号密码登录
    driver.find_element(By.ID, 'switcher_plogin').click()
    driver.implicitly_wait(wait_time)
    time.sleep(1)

    # 登录
    driver.find_element(By.ID, 'u').send_keys(qq_account)
    driver.find_element(By.ID, 'p').send_keys(qq_password)
    driver.implicitly_wait(wait_time)
    time.sleep(1)

    driver.find_element(By.ID, 'login_button').click()
    driver.implicitly_wait(wait_time)
    time.sleep(1)

    # 切出iframe
    driver.switch_to.default_content()


def save_screenshot(ele):
    # 保存整屏幕截图
    name = str(time.time())[:10]
    img = tmp_img_dir + name + '.png'
    driver.save_screenshot(img)

    # PIL打开图片
    im = Image.open(img)

    # 选区
    # 因为设置显示器大小为1366x768，selenium在加载完后会有一个向下滚动操作
    # 174 根据截图位置进行调整
    left = location['x']
    top = location['y'] - 174
    right = location['x'] + size['width']
    bottom = location['y'] + size['height'] - 174

    # 裁剪并保存
    im = im.crop((left, top, right, bottom))
    im.save(img)

    return img


def prepare():
    # 进入游戏页面
    driver.get(game_page)

    # 等待读条完成
    time.sleep(10)

    # 游戏窗口(左上位置，尺寸)
    ele = driver.find_element(By.ID, "FlashContainId")
    global location
    global size
    location = ele.location
    size = ele.size

    action_chains = ActionChains(driver)

    # 点击'开始游戏'
    action_chains.move_to_element_with_offset(ele, 250, 420).click().perform()
    time.sleep(3)

    # 点击'已准备好'
    action_chains.move_to_element_with_offset(ele, 320, 190).click().perform()
    time.sleep(5)


def getCirclePos(img_path):
    # load the image, clone it for output, and then convert it to grayscale
    image = cv2.imread(img_path)
    output = image.copy()
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # detect circles in the image
    circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 50)

    # ensure at least some circles were found
    if circles is not None:
        # convert the (x, y) coordinates and radius of the circles to integers
        circles = np.round(circles[0, :]).astype("int")

        # loop over the (x, y) coordinates and radius of the circles
        for (x, y, r) in circles:
            print
            x, y, r, img_path.split('/')[-1]
            return (x, y)
    else:
        return False


if __name__ == '__main__':

    login()

    prepare()

    ele = driver.find_element(By.ID, "FlashContainId")

    while 1:

        # 保存截图
        img_path = save_screenshot(ele)

        # 解析出圆坐标
        # 不能解析则循环尝试，手动点击处理
        try:
            x, y = getCirclePos(img_path)
        except TypeError:
            print
            "can't find circle"
            time.sleep(3)
            continue

        # 点击
        action_chains = ActionChains(driver)
        action_chains.move_to_element_with_offset(ele, x, y).click().perform()

        time.sleep(2)